package control;

import javax.microedition.lcdui.Graphics;

import main.Res;

public class ListBox extends Control{
	protected int nRow;
	protected int nCol;
	protected int cellWidth;
	protected int cellHeight;
	protected int x;
	protected int y;
	protected int[] icons;
	//protected String[] texts;
	protected int sellectIndex;
	protected boolean isPressed;
	public int getSellectIndex() {
		return sellectIndex;
	}

	public void setSellectIndex(int sellectIndex) {
		this.sellectIndex = sellectIndex;
	}

	
	public ListBox(int nCol,int nRow,int x,int y,int cellW,int cellH) {
		this.nRow = nRow;
		this.nCol = nCol;
		this.x = x;
		this.y = y;
		this.cellWidth = cellW;
		this.cellHeight = cellH;
		icons = new int[nRow*nCol];
		//texts = new String[nRow*nCol];
		sellectIndex = -1;
		isPressed = false;
	}
	
	public void setInfo(int index,int icon){
		icons[index] = icon;
		//texts[index] = text;
	}
	public int getInfo(int index){
		return icons[index];
		//texts[index] = text;
	}
	public int getInfo(){
		if(sellectIndex == -1){
			return -1;
		}
		return icons[sellectIndex];
		//texts[index] = text;
	}
	public void clear(){
		for (int i = 0; i < icons.length; i++) {
			this.icons[i] = -1;
		}
	}
	public int getSize(){
		return icons.length;
	}
	public void setInfo(int[] icons){
		for (int i = 0; i < icons.length; i++) {
			if(i<icons.length){
				this.icons[i] = icons[i];
			}else{
				this.icons[i] = -1;
			}
		}
		
	}
	public boolean pointerPressed(int x,int y)
	{
		if((y-this.y)<0)
		{
			return false;
		}
		int i = (x-this.x)/cellWidth;
		int j = (y-this.y)/cellHeight;
		if(i>=0 && i<nCol && j>=0 && j<nRow ){
			sellectIndex = i+j*nCol;
			isPressed = true;
			return true;
		}
		//sellectIndex = -1;
		return false;
	}
	
	public boolean pointerReleased(int x,int y)
	{
		
		isPressed = false;
		if((y-this.y)<0)
		{
			return false;
		}
		int i = (x-this.x)/cellWidth;
		int j = (y-this.y)/cellHeight;
		
		if(i>=0 && i<nCol && j>=0 && j<nRow ){
			sellectIndex = i+j*nCol;
			if(command!= null)
			{
				Res.PlaySound(4);
				command.Do();
			}
			return true;
		}
		//sellectIndex = -1;
		return false;
	}
	
	protected void controlPaint(Graphics g) {
		
		g.setColor(COLOR_PRESSED);
		g.fillRect(x, y, cellWidth*nCol, cellHeight*nRow);
		
		for(int i=0;i<nCol;i++){
			for(int j=0;j<nRow;j++){
				int index = i+j*nCol; 
				if(index == sellectIndex)// && isPressed)
				{
					g.setColor(COLOR_BACK);
					g.fillRect(x+i*cellWidth, y+j*cellHeight, cellWidth, cellHeight);
				}				
				g.setColor(COLOR_FORE);
				g.drawRect(x+i*cellWidth, y+j*cellHeight, cellWidth, cellHeight);

				Res.drawIcon(g, icons[index],
						x+i*cellWidth+(cellWidth-Res.ICON_SIZE)/2,
						y+j*cellHeight+(cellHeight-Res.ICON_SIZE)/2);
				
			}
		}
	}
}
